/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ships.io.plugins.common;

import java.io.IOException;
import ships.io.stream.ImageInputStream;
import ships.io.stream.ImageInputStreamImpl;

/**
 *
 * @author fqhuy
 */
public final class SubImageInputStream extends ImageInputStreamImpl {

    ImageInputStream stream;
    long startingPos;
    int startingLength;
    int length;

    public SubImageInputStream(ImageInputStream stream, int length)
        throws IOException {
        this.stream = stream;
        this.startingPos = stream.getStreamPosition();
        this.startingLength = this.length = length;
    }

    @Override
    public int read() throws IOException {
        if (length == 0) { // Local EOF
            return -1;
        } else {
            --length;
            return stream.read();
        }
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (length == 0) { // Local EOF
            return -1;
        }

        len = Math.min(len, length);
        int bytes = stream.read(b, off, len);
        length -= bytes;
        return bytes;
    }

    public long length() {
        return startingLength;
    }


    @Override
    public void seek(long pos) throws IOException {
        stream.seek(pos - startingPos);
        streamPos = pos;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        // Empty finalizer (for improved performance; no need to call
        // super.finalize() in this case)
    }
}